from django import template
from django.db.models import Max, Min, Count
from django.apps import apps


register = template.Library()

def required_set(list, last=False):

    """ Получаем нужный набор данных """

    set = list.order_by('-updated')

    if last:
        return set[:last]
    else:
        return set


def sort(list):

    """ Сортируем список частей речи """

    result = list.annotate(last=Max('words__updated'), count=Count('words')) \
                   .order_by('-last')
    return result


def get_related_objects(content_type):
    
    """ Получаем список связанных объектов """

    print(f'model - {content_type}')
    model = apps.get_model(app_label='content', model_name=content_type)
    print(f'model - {model}')
    list_of_related_objects = model.objects.all().order_by('-updated')
    return list_of_related_objects


register.filter('sort', sort)
register.filter('required_set', required_set)
register.filter('get_related_objects', get_related_objects)
